package com.baoyang.service.impl;

import com.baoyang.entity.BaoyangMenu;
import com.baoyang.mapper.BaoyangMenuMapper;
import com.baoyang.service.BaoyangMenuService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BaoyangMenuServiceImpl implements BaoyangMenuService {
    @Resource
    private BaoyangMenuMapper baoyangMenuMapper;

    @Override
    public List<BaoyangMenu> getMenu() {
        List<BaoyangMenu> baoyangMenus = baoyangMenuMapper.selectList(null);
        if (!CollectionUtils.isEmpty(baoyangMenus)) {
            // 1. 先将所有菜单对象放到一个 Map 里，方便通过 id 查找
            Map<Long, BaoyangMenu> menuMap = new HashMap<>();
            for (BaoyangMenu menu : baoyangMenus) {
                menuMap.put(menu.getId(), menu);
            }

            // 2. 创建一个用于存放顶级菜单的列表
            List<BaoyangMenu> rootMenus = new ArrayList<>();

            // 3. 遍历所有菜单，根据 parentId 归类
            for (BaoyangMenu menu : baoyangMenus) {
                if (menu.getParentId() == null || menu.getParentId() == 0) {
                    // 没有父级，说明是顶级菜单
                    rootMenus.add(menu);
                } else {
                    // 有父级，找到父级并添加到其 children
                    BaoyangMenu parent = menuMap.get(menu.getParentId());
                    if (parent != null) {
                        if (parent.getChildren() == null) {
                            parent.setChildren(new ArrayList<>());
                        }
                        parent.getChildren().add(menu);
                    }
                }
            }
            return rootMenus;
        }
        return new ArrayList<>();
    }
}